//
//  WAAddCityViewController.m
//  WeatherApp
//
//  Created by Yuliya Grasevych on 02.09.14.
//  Copyright (c) 2014 Yuliya Grasevych. All rights reserved.
//

#import "WAAddCityViewController.h"
#import "WAYahooInfoProvider.h"
#import "WAWeatherProvider.h"
#import "WALocation.h"

#import "WALoaderView.h"

@interface WAAddCityViewController () <NSTableViewDelegate>
@property (weak) IBOutlet NSSearchField *searchField;
@property (weak) IBOutlet NSTableView *tableView;
@property (weak) IBOutlet NSView *controlView;
@property (weak) IBOutlet NSButton *addButton;
- (IBAction)add:(id)sender;
- (IBAction)cancel:(id)sender;

@end

@implementation WAAddCityViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (IBAction)add:(id)sender
{
    [[WAWeatherProvider sharedInstance] addLocation:self.citiesArrayController.selectedObjects[0]];
    [self close];
}

- (IBAction)cancel:(id)sender
{
    [self close];
}

-(void)close
{
    [self.view.window.sheetParent endSheet:self.view.window];
}

-(void)controlTextDidChange:(NSNotification *)obj
{
    [WALoaderView showLoaderOnView:self.controlView];
    [obj.object setEditable:NO];
    [self requestQuery:[obj.object stringValue]];
    
}

-(NSArray *)cities
{
    if (!_cities) {
        
        _cities = [NSArray array];
    }
    return _cities;
}

-(void)requestQuery:(NSString *)query
{
    NSDictionary *request = @{@"q": [NSString stringWithFormat:@"select * from geo.placefinder where text=\"%@\"", query],
                              @"format": @"json"};
    [[WAYahooInfoProvider sharedInstance] yahooRequestWithStatement:request completionHandler:^(NSError *error, NSDictionary *jsonData) {
        
        [self.citiesArrayController removeObjects:self.cities];
        
        if (!error) {
            
            NSDictionary *query = [jsonData objectForKey:@"query"];
            NSDictionary *results = [query objectForKey:@"results"];
            if (results && ![results isEqualTo:[NSNull null]]) {
                
                id Result = [results objectForKey:@"Result"];
                
                if ([Result isKindOfClass:[NSArray class]]) {
                    
                    
                    [Result enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                        
                        NSString *woeid = [obj objectForKey:@"woeid"];
                        WALocation *location = [[WALocation alloc]initWithWoeid:woeid];
                        location.city = ([[obj objectForKey:@"neighborhood"] isEqualTo:[NSNull null]] ? nil : [obj objectForKey:@"neighborhood"]);
                        
                        location.country = ([[obj objectForKey:@"country"] isEqualTo:[NSNull null]] ? nil : [obj objectForKey:@"country"]);
                        
                        location.district = ([[obj objectForKey:@"county"] isEqualTo:[NSNull null]] ? nil : [obj objectForKey:@"county"]);
                        if (!location.district) {
                            
                            location.district = ([[obj objectForKey:@"state"] isEqualTo:[NSNull null]] ? nil : [obj objectForKey:@"state"]);
                        }
                        
                        [self.citiesArrayController addObject:location];
                    }];
                }
                else if ([Result isKindOfClass:[NSDictionary class]]) {
                    
                    NSString *woeid = [Result objectForKey:@"woeid"];
                    WALocation *location = [[WALocation alloc]initWithWoeid:woeid];
                    location.city = ([[Result objectForKey:@"neighborhood"] isEqualTo:[NSNull null]] ? nil : [Result objectForKey:@"neighborhood"]);
                    
                    location.country = ([[Result objectForKey:@"country"] isEqualTo:[NSNull null]] ? nil : [Result objectForKey:@"country"]);
                    
                    location.district = ([[Result objectForKey:@"county"] isEqualTo:[NSNull null]] ? nil : [Result objectForKey:@"county"]);
                    if (!location.district) {
                        
                        location.district = ([[Result objectForKey:@"state"] isEqualTo:[NSNull null]] ? nil : [Result objectForKey:@"state"]);
                    }
                    CLLocation *locationCoordinates = [[CLLocation alloc] initWithLatitude:[[Result objectForKey:@"latitude"] floatValue] longitude:[[Result objectForKey:@"longitude"] floatValue]];
                    location.location = locationCoordinates;
                    
                    [self.citiesArrayController addObject:location];
                }
            }
            [WALoaderView removeLoaderFromView:self.controlView];
            [self.searchField setEditable:YES];
            
        }
    }];
}

#pragma mark - TableView Delegate

-(void)tableViewSelectionDidChange:(NSNotification *)notification
{
    if (self.tableView.selectedRow >= 0) {
        
        [self.addButton setEnabled:YES];
    }
    else {
        
        [self.addButton setEnabled:NO];
    }
}

@end
